package com.moore.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.moore.bean.Apartment;
import com.moore.bean.TenantInfo;
import com.moore.dto.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import com.moore.service.AuditService;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

import static com.moore.utils.Logger.toLog;

@Controller
@RequestMapping("/audit")
public class AuditController {
    @Autowired
    private AuditService auditService;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @RequestMapping("/get")
    @ResponseBody
    public ResponseData getAuditList(@RequestBody TenantInfo tenantInfo) {
        toLog("正在获取审核列表");
        return auditService.getAuditList(tenantInfo);
    }

    @RequestMapping("/audit")
    @ResponseBody
    public ResponseData auditTenant(@RequestBody List<TenantInfo> tenantInfo) {
        toLog("正在审核租客");
        return auditService.auditTenant(tenantInfo);
    }

    @RequestMapping("/allocate")
    @ResponseBody
    public ResponseData allocateApartment(@RequestBody Map<String, Object> params) {
        try {
            TenantInfo tenantInfo = objectMapper.convertValue(params.get("tenantInfo"), TenantInfo.class);
            Apartment apartment = objectMapper.convertValue(params.get("apartment"), Apartment.class);
            if (tenantInfo == null || apartment == null) return new ResponseData(500,"参数错误",null,0);
            return auditService.allocateApartment(tenantInfo, apartment);
        } catch (Exception e){
            e.printStackTrace();
            return new ResponseData(500,"系统错误",null,0);
        }
    }

    @RequestMapping("/allocateBatch")
    @ResponseBody
    public ResponseData allocateApartments(@RequestBody List<TenantInfo> tenants) {
        toLog("正在批量分配公寓");
        return auditService.allocateApartments(tenants);
    }

    @RequestMapping("/allocateSave")
    @ResponseBody
    public ResponseData allocateSave(@RequestBody Map<String, Object> params) {
        try {
            List<TenantInfo> tenants = objectMapper.convertValue(params.get("tenantInfo"), objectMapper.getTypeFactory().constructCollectionType(List.class, TenantInfo.class));
            List<Apartment> apartments = objectMapper.convertValue(params.get("apartment"), objectMapper.getTypeFactory().constructCollectionType(List.class, Apartment.class));
            if (tenants == null || apartments == null) return new ResponseData(500,"参数错误",null,0);
            return auditService.allocateSave(tenants, apartments);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(500, "系统错误", null, 0);
        }
    }
}
